//
//  GroupDetailHeadCell.swift
//  YueChat
//
//  Created by IMac on 2024/10/8.
//

import UIKit

protocol GroupDetailHeadDelegate : AnyObject {
    
    func FriendAddBlock ()
    func FriendLessBlock ()
    func FriendSeeBlock (index:Int)
    func FriendSeeMoreBlock ()
}


class GroupDetailHeadCell: UITableViewCell, UICollectionViewDelegate, UICollectionViewDataSource {
    
    var data = [DMCCMember]()
    var isManager = Bool()
    var isMore = Bool()
    var info = DMCCGroup()
    weak var delegate:GroupDetailHeadDelegate?
    
    lazy var layout: UICollectionViewFlowLayout = {
        
        let layout = UICollectionViewFlowLayout()
        layout.itemSize = CGSize(width: kScreenWidth/6, height: 70)
        layout.minimumLineSpacing = 0
        layout.minimumInteritemSpacing = 0
        layout.scrollDirection = .vertical
        layout.sectionInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
        return layout
    }()
    
    lazy var countLab : UILabel = {
        let countLab = UILabel()
        countLab.textAlignment = .center
        countLab.font = UIFont.systemFont(ofSize: 13)
        countLab.textColor = UIColor.gray
        return countLab
    }()
    
    lazy var allBtn : UIButton = {
        let allBtn = UIButton(type: .custom)
        allBtn.setTitle("查看全部成员", for: .normal)
        allBtn.setTitleColor(UIColor.gray, for: .normal)
        allBtn.addTarget(self, action: #selector(moreClick), for: .touchUpInside)
        return allBtn
    }()
    
    lazy var collectionView: UICollectionView = {
        let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
        collectionView.dataSource = self
        collectionView.backgroundColor = UIColor.red
        collectionView.delegate = self
        collectionView.isUserInteractionEnabled = true
        return collectionView
    }()

    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        self.selectionStyle = .none
        self.addSubview(collectionView)
        
        addSubview(allBtn)
        GK_main_async_safe { [self] in
            allBtn.snp.makeConstraints { make in
                make.left.right.equalTo(self.contentView)
                make.height.equalTo(40)
                make.bottom.equalTo(self)
            }
        }
        
        addSubview(countLab)
        
        countLab.snp.makeConstraints { make in
            make.left.right.equalTo(self.contentView)
            make.height.equalTo(20)
            make.bottom.equalTo(allBtn.snp.top).offset(-10)
        }
        
        collectionView.snp.makeConstraints { make in
            make.left.right.equalTo(self.contentView)
            make.top.equalTo(self)
            make.bottom.equalTo(countLab.snp.top).offset(0)
        }
        
        collectionView.register(UINib(nibName: "GroupDetailHeadImgCell", bundle: nil), forCellWithReuseIdentifier: "GroupDetailHeadImgCell")
    }
    
    func update () {
        countLab.text = "\(KLocalizedString("MaxMembersCountString"))\(info.maxMemberCount)\(KLocalizedString("People"))"
        self.collectionView.reloadData()
    }
    
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
        
    }
    
    
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }

    
    func updateAllBtn (isShow:Bool) {
        if isShow {
            allBtn.snp.updateConstraints { make in
                make.height.equalTo(40)
            }
            allBtn.isHidden = false
        }else{
            allBtn.snp.updateConstraints { make in
                make.height.equalTo(0)
            }
            allBtn.isHidden = true
        }
    }
    
    @objc func moreClick () {
        self.delegate?.FriendSeeMoreBlock()
    }
    
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if (self.isManager) {
            if (self.isMore) {
                updateAllBtn(isShow: true)
            } else {
                updateAllBtn(isShow: false)
            }
            return self.data.count + 2;
        } else {
            if (self.isMore) {
                updateAllBtn(isShow: true)
            } else {
                updateAllBtn(isShow: false)
            }
            return self.data.count + 1;
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "GroupDetailHeadImgCell", for: indexPath) as! GroupDetailHeadImgCell
        if indexPath.row == data.count {
//            if  !isManager {
//            } else {
//                cell.img.image = UIImage(named: "f_add")
//            }
            cell.img.image = UIImage(named: "f_add")
            cell.nameLab.isHidden = true
            cell.nftImg.isHidden = true
        } else if indexPath.row == data.count + 1 ,isManager {
            cell.img.image = UIImage(named: "f_less")
            cell.nameLab.isHidden = true
            cell.nftImg.isHidden = true
        } else {
            cell.nameLab.isHidden = false
            
            let member = data[indexPath.row]
            let groupId = member.groupId
            let memberId = member.memberId
            
            //let user = gosnUser.getUserInfo(memberId, inGroup: groupId, refresh: false)
            let user = gosnUser.getUserInfoDefault(memberId)

            cell.nameLab.text = user.getDisplayName()
            cell.img.sd_setImage(with: URL(string: user.portrait), placeholderImage: SDImageDefault)

            let nftStr = user.nft
            cell.nftImg.isHidden = nftStr.isEmpty
        }

            return cell
    }
    
//    func isManager () -> Bool {
//        let str = self.info.getGroupJoinTypeWithGroupId()
//        return str == "admin"
//    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if indexPath.row == self.data.count {
            //let str = self.info.getGroupJoinTypeWithGroupId()
            let str = self.info.joinType
            if str == OsnJoinType.admin {
                if !isManager {
                    return
                }
            }
            self.delegate?.FriendAddBlock()
            
        } else if indexPath.row == self.data.count + 1 && isManager {
            self.delegate?.FriendLessBlock()
        } else {
            self.delegate?.FriendSeeBlock(index: indexPath.row)
        }
    }

}
